package com.pastock.zookeepermanager;

import java.io.IOException;
import java.util.Map;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.pastock.zookeepermanager.ZookeeperDataMonitor.ZookeeperDataMonitorListener;




/**
 * 初始化Zookeeper
 * @author LIANGXI723
 *
 */
@Component
public class InitZooKeeperInfo implements Watcher, ZookeeperDataMonitorListener,InitializingBean{
	
	@Value("${frontend.zookeeper.connect}")
	private String connectString;
	
	@Value("${frontend.zookeeper.timeout}")
	private Integer  sessionTimeout;
	
	@Value("${frontend.zookeeper.path}")
	private String path;
	@Autowired
	private ZookeeperDataMonitor dm;
   
	ZooKeeper zk;
         
	public void exists(byte[] data) {
		
	}
	public static String getConfig(String configName){
		Map<String,String> zkConfigMap = ZookeeperConfigrutionConstant.getZookeeperConfigrutionConstantMap();
    	return zkConfigMap.get(configName);
    }
	
	public void closing(int rc) {
		try {
			System.out.println("close session It's all over");
			System.out.println("zk1:"+zk);
			//关闭现有的zk线程
			zk.close();
			
			System.out.println("zk2:"+zk);
			//重新建立新的zk连接
			zk = new ZooKeeper(connectString, sessionTimeout, this);
			dm.monitor(zk, path, null, this);
			System.out.println("zk3:"+zk);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void process(WatchedEvent event) {
		dm.process(event);
	}

	public void setConnectString(String connectString) {
		this.connectString = connectString;
	}

	public void setSessionTimeout(Integer sessionTimeout) {
		this.sessionTimeout = sessionTimeout;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public void afterPropertiesSet() throws Exception {
    	System.out.println("Init Zookeeper Data, connectString:"+connectString+" sessionTimeout:"+sessionTimeout+" znode:"+path);
		try {
			zk = new ZooKeeper(connectString, sessionTimeout, this);
			dm = new ZookeeperDataMonitor();
			dm.monitor(zk, path, null, this);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
